package com.huajx.jrb.service;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.huajx.jrb.model.Archive;
import com.huajx.util.bean.BeanUtil;
import com.huajx.util.date.DatePattern;
import com.huajx.util.date.DateUtil;
import com.huajx.util.io.FileUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

public class ArchiveService extends BaseService<Archive> {
    public final static ArchiveService service = new ArchiveService(Archive.class);

    private ArchiveService(Class<Archive> modelClass) {
        super(modelClass);
    }

    /**
     * 生成模板文档
     *
     * @param archive
     * @return
     */
    public String exportDoc(Archive archive) throws Exception {
        File file = FileUtil.file("tpl/governmentFile.docx");

        if(!file.exists()){
            return "";
        }

        Map<String, Object> map = BeanUtil.beanToMap(archive, true, true);

        map.put("receipt", DateUtil.format(archive.getReceipt(), DatePattern.NORM_DATE_FORMAT));

        XWPFDocument document = WordExportUtil.exportWord07(file.getAbsolutePath(), map);

        String fileName = "files/archive/" + archive.getId()+".docx";
        File outFile = FileUtil.file(fileName);

        if(!outFile.exists()){
            FileUtil.touch(outFile);
        }

        FileOutputStream fos = new FileOutputStream(FileUtil.file(fileName));
        document.write(fos);
        fos.close();
        return fileName;
    }
}
